// 个人主页
import { useEffect, useState } from 'react'
import request from '../api/request'
import './PatientProfile.css'

interface SickCircleItem {
  sickCircleId: number
  title: string
  detail: string
  amount: number
  collectionNum: number
  commentNum: number
  releaseTime: number
}

interface ListResponse {
  result: SickCircleItem[]
  message: string
  status: string
}

export interface PatientProfileProps {
  patientUserId: string | number
  nickName?: string
  headPic?: string
  pageSize?: number
}

const PatientProfile = ({ patientUserId, nickName = 'TA', headPic = '', pageSize = 10 }: PatientProfileProps) => {
  const [posts, setPosts] = useState<SickCircleItem[]>([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    fetchList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [patientUserId])

  const fetchList = async () => {
    try {
      setLoading(true)
      const res = await request.get('/health/user/sickCircle/v1/findPatientSickCircleList', {
        params: { patientUserId, page: 1, count: pageSize }
      }) as ListResponse
      setPosts(Array.isArray(res.result) ? res.result : [])
    } catch (e) {
      console.error('获取个人病友圈失败', e)
      setPosts([])
    } finally {
      setLoading(false)
    }
  }

  const formatTime = (ts: number) => {
    const d = new Date(ts)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const h = String(d.getHours()).padStart(2, '0')
    const mi = String(d.getMinutes()).padStart(2, '0')
    return `${y}-${m}-${day} ${h}:${mi}`
  }

  return (
    <div className="user-page">
      <div className="user-header">
        <div className="cover" />
        <div className="user-row">
          <img className="user-avatar" src={headPic} alt={nickName} />
          <div className="user-name">{nickName}</div>
        </div>
      </div>

      <div className="user-section-title">他发布的病友圈</div>

      {loading ? (
        <div className="user-loading">加载中...</div>
      ) : (
        <div className="user-posts">
          {posts.map(p => (
            <div key={p.sickCircleId} className="user-post">
              <div className="post-title">{p.title}</div>
              <div className="post-time">{formatTime(p.releaseTime)}</div>
              <div className="post-detail">{p.detail}</div>
              <div className="post-meta">
                <span>收藏 {p.collectionNum}</span>
                <span>建议 {p.commentNum}</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

export default PatientProfile
